package com.jymj.common.quartz.controller;

import com.jymj.common.quartz.constant.GloabalConstant;
import com.jymj.common.quartz.entity.QuartzJobModule;
import com.jymj.common.quartz.entity.QuartzJobsVO;
import com.jymj.common.quartz.qzComp.TaskJobDetail;
import com.jymj.common.quartz.utils.CronUtil;
import com.jymj.common.quartz.utils.QuartzJobComponent;
import com.jymj.utils.R;
import org.quartz.CronTrigger;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.TriggerKey;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @description: quartz controller 。
 * @version 1.0.0
 * @errorcode
 *            错误码: 错误描述
 * @author
 *         <li>2020-09-04 825338623@qq.com Create 1.0
 * @copyright ©2019-2020
 */
@RestController
@RequestMapping("/quartz/job")
public class JobController {
    private final static Logger LOGGER = LoggerFactory.getLogger(JobController.class);
    
    @Autowired
    private QuartzJobComponent quartzJobComponent;
    @Autowired
    private SchedulerFactoryBean springScheduler;

    @RequestMapping("/add")
    @ResponseBody
    public R save(@RequestBody QuartzJobModule quartzJobModule) {
        LOGGER.info("新增任务");
        try {
            //QuartzJobModule quartzJobModule = new QuartzJobModule();
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, 2020);
            cal.set(Calendar.MONTH, 8);
            cal.set(Calendar.DATE, 9);
            cal.set(Calendar.HOUR_OF_DAY, 12);
            cal.set(Calendar.MINUTE, 30);
            cal.set(Calendar.SECOND, 00);
            //Date startDate = cal.getTime();// 任务开始日期为2020年9月9日12点30分
            Date startDate = quartzJobModule.getStartTime();// 任务开始日期为2020年9月9日12点30分

            Calendar endCal = Calendar.getInstance();
            endCal.set(Calendar.YEAR, 2020);
            endCal.set(Calendar.MONTH, 8);
            endCal.set(Calendar.DATE, 12);
            endCal.set(Calendar.HOUR_OF_DAY, 12);
            endCal.set(Calendar.MINUTE, 30);
            endCal.set(Calendar.SECOND, 00);
            //Date endDate = endCal.getTime();// 任务结束日期为2020年9月12日12点30分
            Date endDate = quartzJobModule.getEndTime();// 任务结束日期为2020年9月12日12点30分

            quartzJobModule.setStartTime(CronUtil.getStartDate(startDate));
            quartzJobModule.setEndTime(CronUtil.getEndDate(endDate));
            // 注意：在后面的任务中需要通过这个JobName来获取你要处理的数据，因此您可以讲这个设置为你要处理的数据的主键，比如id
            //quartzJobModule.setJobName("testJobId");
            //quartzJobModule.setTriggerName("tesTriggerNmae");
            quartzJobModule.setJobGroupName(GloabalConstant.QZ_JOB_GROUP_NAME);
            quartzJobModule.setTriggerGroupName(GloabalConstant.QZ_TRIGGER_GROUP_NAME);
/*            String weeks = "1,2,3,5";// 该处模拟每周1,2,3,5执行任务
            String cronExpression = CronUtil.convertCronExpression(startDate,
                    endDate, weeks.split(","));
            quartzJobModule.setCron(cronExpression);*/
            quartzJobModule.setJobClass(TaskJobDetail.class);
            quartzJobComponent.addJob(quartzJobModule);
        }
        catch (Exception e) {
            e.printStackTrace();
            return R.ok();
        }
        return R.ok();
    }
    
    @RequestMapping("/edit")
    @ResponseBody
    public R edit(@RequestBody QuartzJobModule quartzJobModule) {
        LOGGER.info("编辑任务");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2020);
        cal.set(Calendar.MONTH, 8);
        cal.set(Calendar.DATE, 12);
        cal.set(Calendar.HOUR_OF_DAY, 12);
        cal.set(Calendar.MINUTE, 30);
        cal.set(Calendar.SECOND, 00);
        //Date startDate = cal.getTime();// 任务开始日期为2020年9月12日12点30分
        Date startDate = quartzJobModule.getStartTime();// 任务开始日期为2020年9月12日12点30分

        Calendar endCal = Calendar.getInstance();
        endCal.set(Calendar.YEAR, 2020);
        endCal.set(Calendar.MONTH, 8);
        endCal.set(Calendar.DATE, 24);
        endCal.set(Calendar.HOUR_OF_DAY, 12);
        endCal.set(Calendar.MINUTE, 30);
        endCal.set(Calendar.SECOND, 00);
        //Date endDate = endCal.getTime();// 任务结束日期为2020年9月24日12点30分
        Date endDate = quartzJobModule.getEndTime();// 任务结束日期为2020年9月24日12点30分
        // "testJobId"为add方法添加的job的name
        quartzJobComponent.modifyJobTime(quartzJobModule.getJobName(), quartzJobModule.getCron(), startDate, endDate);
        return R.ok();
    }
    
    @RequestMapping("/pause")
    @ResponseBody
    public R pause(String jobName) {
        LOGGER.info("停止任务");
        quartzJobComponent.pauseJob(jobName);
        return R.ok();
    }
    
    @RequestMapping("/resume")
    @ResponseBody
    public R resume(String jobName) {
        LOGGER.info("恢复任务");
        quartzJobComponent.resumeJob(jobName);
        return R.ok();
    }

    @RequestMapping("/startJobs")
    @ResponseBody
    public R startJobs() {
        LOGGER.info("启动所有任务");
        quartzJobComponent.startJobs();
        return R.ok();
    }

    @RequestMapping("/shutdownJobs")
    @ResponseBody
    public R shutdownJobs() {
        LOGGER.info("关闭所有任务");
        quartzJobComponent.shutdownJobs();
        return R.ok();
    }
    
    @RequestMapping("/remove")
    @ResponseBody
    public R remove(String jobName) {
        LOGGER.info("移除任务");
        quartzJobComponent.removeJob(jobName);
        return R.ok();
    }

    @RequestMapping("/getTriggerState")
    @ResponseBody
    public R getTriggerState(String jobName) {
        LOGGER.info("获取任务状态");
        String triggerState = quartzJobComponent.getTriggerState(jobName);
        return R.ok(triggerState);
    }

    @RequestMapping("/")
    @ResponseBody
    public List<QuartzJobsVO> getAllJobs() {
        LOGGER.info("获取所有任务");
        List<QuartzJobsVO> quartzJobsVOList = new ArrayList<>();
        try {
            //获取Scheduler
            Scheduler scheduler = springScheduler.getScheduler();
            //再获取Scheduler下的所有group
            List<String> triggerGroupNames = scheduler.getTriggerGroupNames();
            for (String groupName : triggerGroupNames) {
                //组装group的匹配，为了模糊获取所有的triggerKey或者jobKey
                GroupMatcher groupMatcher = GroupMatcher.groupEquals(groupName);
                //获取所有的triggerKey
                Set<TriggerKey> triggerKeySet = scheduler.getTriggerKeys(groupMatcher);
                for (TriggerKey triggerKey : triggerKeySet) {
                    //通过triggerKey在scheduler中获取trigger对象
                    CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
                    //获取trigger拥有的Job
                    JobKey jobKey = trigger.getJobKey();
                    JobDetailImpl jobDetail = (JobDetailImpl) scheduler.getJobDetail(jobKey);
                    //组装页面需要显示的数据
                    QuartzJobsVO quartzJobsVO = new QuartzJobsVO();
                    quartzJobsVO.setGroupName(groupName);
                    quartzJobsVO.setJobName(jobDetail.getName());
                    quartzJobsVO.setJobCronExpression(trigger.getCronExpression());
                    quartzJobsVO.setTimeZone(trigger.getTimeZone().getID());
                    String triggerState = quartzJobComponent.getTriggerState(jobDetail.getName());
                    quartzJobsVO.setStart(triggerState);
                    quartzJobsVOList.add(quartzJobsVO);
                }
            }
        } catch (Exception e) {
            LOGGER.error("获取定时任务信息出错", e);
        }
        return quartzJobsVOList;
    }
}
